package com.dysm.spring.security.resource.service;

import com.alibaba.fastjson.JSONObject;
import com.dysm.spring.security.resource.domain.tongcheng.req.TongChengBaseReq;
import com.dysm.spring.security.resource.domain.tongcheng.req.TongChengSignReq;
import com.dysm.spring.security.resource.domain.tongcheng.resp.TongChengSignResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

@Service
public class TongChengService {

    @Autowired
    private RestTemplate restTemplate;

    private static final Map<String, String> domainMap = new HashMap<>();
    private static final Map<String, String> signKeyMap = new HashMap<>();

    static {
        domainMap.put("test", "https://api.qa.dttrip.cn/openapi/api/");
        domainMap.put("pro", "https://api.dttrip.cn/openapi/api/");
        signKeyMap.put("test", "d6tFWPQ1kVWOKjjx");
        signKeyMap.put("pro", "bz7VJJ6bcsPpT6dv");
    }
    public TongChengSignResp sign(TongChengSignReq signReq, String signKey) {
        String random = UUID.randomUUID().toString();
        String timestamp = Long.toString(new Date().getTime());

        JSONObject jObject = new JSONObject();
        jObject.put("isEncrypt", false);
        jObject.put("random", random);
        jObject.put("timestamp", timestamp);
        jObject.put("accessToken", signReq.getAccessToken());

        JSONObject jParam = signReq.getParam();
//
//        JSONObject jParam = new JSONObject();
//        param.forEach(jParam::put);

        jObject.put("param", jParam);

        String postData = jObject.toJSONString();
        System.out.println(postData);

        // 先将post提交的数据原文算出md5
        String postDataMd5 = getMd5(postData);
        // 再计算 sign
        String sign = getMd5(postDataMd5 + signKey);

        TongChengSignResp resp = new TongChengSignResp();
        resp.setTimestamp(timestamp);
        resp.setEncrypt(Boolean.FALSE);
        resp.setRandom(random);
        resp.setSign(sign);
        return resp;
    }

    private static String getMd5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes(StandardCharsets.UTF_8));
            byte[] b = md.digest();

            int i;

            StringBuilder buf = new StringBuilder("");
            for (byte value : b) {
                i = value;
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            return buf.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5加密异常");
        }
    }

    public String request(TongChengSignReq req, String mapping, String env) {
        String notNullEnv = StringUtils.hasText(env) ? env : "test";
        TongChengSignResp signResp = sign(req, signKeyMap.get(notNullEnv));
        String url = domainMap.get(notNullEnv) + mapping + "?sign=" + signResp.getSign();

        JSONObject jObject = new JSONObject();
        jObject.put("isEncrypt", signResp.getEncrypt());
        jObject.put("random", signResp.getRandom());
        jObject.put("timestamp", signResp.getTimestamp());
        jObject.put("accessToken", req.getAccessToken());

        JSONObject jParam = new JSONObject();
        req.getParam().forEach(jParam::put);

        jObject.put("param", jParam);

        String postData = jObject.toJSONString();
//
//        TongChengBaseReq baseReq = new TongChengBaseReq();
//        baseReq.setAccessToken(req.getAccessToken());
//        baseReq.setParam(req.getParam());
//        baseReq.setRandom(signResp.getRandom());
//        baseReq.setEncrypt(signResp.getEncrypt());
//        baseReq.setTimestamp(signResp.getTimestamp());

        return TestService.postData(postData, url);
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.setAcceptCharset(Collections.singletonList(Charset.defaultCharset()));
////
//        HttpEntity<String> entity = new HttpEntity<>(postData, headers);
////
////        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//
//        byte[] bytes = restTemplate.postForObject(url, entity, byte[].class);
//        assert bytes != null;
//        return new String(bytes, StandardCharsets.UTF_16LE);
    }
}
